<template>
    <div class="ant-modal-content">
        <div class="ant-modal-body">
            <el-form>
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="会员卡号">
                            <el-select v-model="ruleForm.supId" placeholder="请选择会员卡号" >
                                <el-option v-for="item in suppliers" :key="item.supId" :label="item.supName"
                                    :value="item.supId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="单据日期:">
                            <el-date-picker type="datetime" v-model="ruleForm.billDate" placeholder="选择日期与时间"
                                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" clearable
                                class="input" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="单据编号">
                            <el-input v-model="ruleForm.number" readonly placeholder="自动生成" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="关联订单">
                            <el-input v-model="ruleForm.linkNumber" style="width: 240px" suffix-icon="Search"
                                v-perm:retail:retail_back:insert:associateorder="handleIconClick" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <div class="ant-row-flex" style="display: flex; align-items: center; margin-bottom: 10px;">
                            <div class="ant-col" style="margin-right: 10px">
                                <el-button type="primary" class="ant-btn ant-btn-primary" @click="insertTr">
                                    <el-icon class="el-icon-left">
                                        <Plus />
                                    </el-icon>
                                    <span>插入行</span>
                                </el-button>
                            </div>
                            <div>
                                <el-button type="primary" @click="removeSelectedRows" class="ant-btn ant-btn-danger"
                                    v-if="selectedRows.length > 0">
                                    <el-icon class="el-icon-left">
                                        <Minus />
                                    </el-icon>
                                    <span>移除行</span>
                                </el-button>
                            </div>
                            <div class="ant-col" style="margin-right: 10px">
                                <el-button plain>扫码录入</el-button>
                            </div>
                        </div>
                    </el-col>
                </el-row>
                <el-row style="padding: 10px;">
                    <el-col :span="18">
                        <el-table border class="my-custom-table" @selection-change="handleSelectionChange"
                            :data="tableData" show-summary :summary-method="getSummaries" max-height="340">
                            <el-table-column type="selection" width="30" />
                            <el-table-column label="仓库" width="160">
                                <template #default="{ row }">
                                    <el-select v-model="row.depotId" placeholder="选择仓库">
                                        <el-option v-for="warehouse in depots" :key="warehouse.id"
                                            :label="warehouse.name" :value="warehouse.id" />
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column prop="barcode" label="条码" width="160">
                                <template #default="{ row }">
                                    <el-input v-model="row.barCode">
                                      
                                    </el-input>
                                </template>
                            </el-table-column>
                            <el-table-column label="名称" width="160">
                                <template #default="{ row }">
                                    <el-input class="dashed-input" v-model="row.name" />
                                </template>
                            </el-table-column>
                            <el-table-column label="规格" property="shopCode">
                                <template #default="{ row }">
                                    <el-input class="dashed-input" v-model="row.standard" />
                                </template>
                            </el-table-column>
                            <el-table-column label="库存">
                                <template #default="{ row }">
                                    <el-input class="dashed-input" v-model="row.kt" />
                                </template>
                            </el-table-column>
                            <el-table-column label="单位">
                                <template #default="{ row }">
                                    <el-input class="dashed-input" v-model="row.materialUnit" />
                                </template>
                            </el-table-column>
                            <el-table-column label="数量">
                                <template #default="{ row }">
                                    <el-input @input="change(row)" v-model="row.operNumber" />
                                </template>
                            </el-table-column>
                            <el-table-column label="单价">
                                <template #default="{ row }">
                                    <el-input @input="change(row)" v-model="row.unitPrice" />
                                </template>
                            </el-table-column>
                            <el-table-column label="金额">
                                <template #default="{ row }">
                                    <el-input v-model="row.allPrice" />
                                </template>
                            </el-table-column>
                            <el-table-column label="备注">
                                <template #default="{ row }">
                                    <el-input v-model="row.remark" />
                                </template>
                            </el-table-column>
                        </el-table>

                      
                    </el-col>
                    <el-col :span="1" />
                    <el-col :span="5">
                        <el-form-item label="单据金额" data-step="5" data-title="单据金额" data-intro="单据金额等于左侧商品的总金额"
                            class="centered-form-item">
                            <el-input v-model="ruleForm.totalPrice" class="custom-input" readonly />
                        </el-form-item>

                        <el-form-item label="收款金额" prop="changeAmount" data-step="6" data-title="收款金额"
                            data-intro="收款金额为收银员收取用户的实际金额" class="centered-form-item">
                            <el-input v-model="ruleForm.changeAmount" class="custom-input" />
                        </el-form-item>

                        <el-form-item label="找零" data-step="7" data-title="找零" data-intro="找零等于收款金额减去实收金额"
                            class="centered-form-item">
                            <el-input v-model="ruleForm.backAmount" class="custom-input" readonly />
                        </el-form-item>

                        <el-form-item label="收款账户：">
                            <el-select v-model="ruleForm.accountId" placeholder="选择结算账户">
                                <el-option v-for="item in accounts" :key="item.accId" :label="item.name"
                                    :value="item.accId" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row style="margin-top: 300px;">
                    <el-col :span="24" :offset="0">
                        <el-form-item style="float: right">
                            <el-button @click="close">取消</el-button>
                            <el-button @click="submitForm(1)">保存并审核</el-button>
                            <el-button type="primary" @click="submitForm(0)">保存</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
    </div>
    <!-- 弹窗 -->
    <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="65%" top="15vh" style="height: 750px">
        <router-view @close="closeAdd" @saveSaleinorder="saveSaleinorder" @subdocument="subdocument"
            :data="data"></router-view>
    </el-dialog>
</template>

<script setup>
import { ref, defineEmits, onMounted, watch } from 'vue';
import router from "@/router";
import request from "@/api/request";
import { ElMessage } from 'element-plus';

let title = ref("");
let visible = ref(false);
let emits = defineEmits(["close"]);
let data = defineProps(["data"])
let formData = data.data
console.log('formData1111', formData)
let id = formData.id

// 会员卡信息
let suppliers = ref([]);
// 收款账户信息
const accounts = ref([{ accId: 1 }]);
// 收款类型状态
const payTypes = ref([
    { label: "现付", value: "现付" },
    { label: "预付款", value: "预付款" },
]);

let tableData = ref([{ operNumber: 0, allPrice: 0 }]);


let ruleForm = ref({
    billDate: formData.operTime,
    organId: formData.supId,
    number: formData.number,
    linkNumber: formData.linkNumber,
    remark: formData.remark,
    discountRate: formData.discount,
    paymentDiscount: formData.discountMoney,
    discountedAmount: formData.discountLastMoney,
    documentnumber: formData.changeAmount,
    accountId: formData.accountId,
    otherMoney: formData.otherMoney,
    debt: formData.debt
});

// 在组件加载时调用该方法
onMounted(() => {
    // 直接使用 formData 来初始化表单字段
    ruleForm.value.billDate = new Date().toISOString().slice(0, 19).replace('T', ' ') || ''; // 当前时间格式化为 'YYYY-MM-DD HH:mm:ss'
    ruleForm.value.supId = formData.supId || '';
    ruleForm.value.number = formData.number || '';
    ruleForm.value.linkNumber = formData.linkNumber || '';
    ruleForm.value.remark = formData.remark || '';

    // 重要：将传入的单据金额赋值给 totalPrice
    ruleForm.value.totalPrice = formData.totalPrice || 0; // 初始化单据金额

    // 如果需要，可以也将初始化收款金额为单据金额
    ruleForm.value.changeAmount = ruleForm.value.totalPrice; // 可选

    // 加载供应商和账户信息
    findsuppliers();
    findaccounts();
});
const handleIconClick = (menu) => {
    title.value = "选择零售出库";
    visible.value = true;
    router.push(menu.path);
}

// 插入一条数据
const insertTr = () => {
    tableData.value.push({
        operNumber: 0,
        allPrice: 0,
    });
};

// 查询会员信息
const findsuppliers = () => {
    request({
        url: "/basic/vendor/findSupplier3",
        method: "get",
    }).then((resp) => {
        suppliers.value = resp.data;
    });
};


// 查询仓库数据
const depots = ref([]);
const loadDepot = () => {
    request({
        url: '/depot/list',
        method: 'get'
    }).then(res => {
        depots.value = res.data;
        if (tableData.value.length > 0) {
            tableData.value.forEach(row => {
                row.depotId = depots.value.length > 0 ? depots.value[0].id : null;
            });
        }
    }).catch(err => {
        console.error(err);
    });
};
loadDepot();

// 查询结算用户
const findaccounts = () => {
    request({
        url: "/basic/account/list",
        method: "get",
    }).then((resp) => {
        accounts.value = resp.data;
    });
};



// 计算单据金额
const calculateInvoiceAmount = () => {
    ruleForm.value.totalPrice = tableData.value.reduce((total, row) => total + (row.allPrice || 0), 0);
};


// 计算找零
const calculateChange = () => {
    ruleForm.value.backAmount = Math.max(0, (ruleForm.value.changeAmount || 0) - (ruleForm.value.totalPrice || 0));
};
// 监控收款金额 (changeAmount) 的变化
watch(() => ruleForm.value.changeAmount, () => {
    calculateChange(); // 每次收款金额变化时更新找零
});

//根据headerId查询子单据
let findById = () => {
    request.get("/purchase/order/findById/" + id)
        .then(resp => {
            console.log("9999",resp.data)
            tableData.value = resp.data
        })
}
findById();


const selectedRows = ref([]);

const handleSelectionChange = (selected) => {
  selectedRows.value = selected;
};

const removeSelectedRows = () => {
  const selectedBarcodes = selectedRows.value.map(row => row.barcode);
  tableData.value = tableData.value.filter(row => !selectedBarcodes.includes(row.barcode));
  selectedRows.value = []; // 清空选中的行
};

// 接收并显示保存的数据
const saveSaleinorder = (selectedItems) => {
    tableData.value = selectedItems.map((item) => ({
        barCode: item.barCode,
        categoryName: item.categoryName,
        commodityUnit: item.commodityUnit,
        materialName: item.materialName,
        mfrs: item.mfrs,
        model: item.model,
        sku: item.sku,
        standard: item.standard,
        totalIn: item.totalIn,
        remark: item.remark,
        totalOperNumber: item.totalOperNumber,
        totalOut: item.totalOut,
        wholesaledecimal: item.wholesaledecimal,
        basicnumber: item.basicnumber,
        allprice: item.allprice,
        mid: item.mid,
        aid: item.aid,
        operNumber: 1,
        allPrice: 1 * item.wholesaledecimal,
    }));
    calculateInvoiceAmount(); // 重新计算单据金额
};

// 初始收款金额值
const initialReceiveAmount = ref(0);

// input计算绑定
const change = (row) => {
    row.allPrice = row.operNumber * row.unitPrice;
    calculateInvoiceAmount(); // 重新计算单据金额

    // 将收款金额更新为单据金额
    ruleForm.value.changeAmount = ruleForm.value.totalPrice;
}



//接收关联订单数据
let subdocument = (items, selectedItems) => {
    console.log("items", items);
    console.log("selectedItems", selectedItems);

    // 检查 selectedItems 是否有值并赋值给 ruleForm
    if (selectedItems && selectedItems.length > 0) {
        const selectedItem = selectedItems[0]; // 获取第一个选中的项目
        // 从 selectedItem 提取信息并赋值给 ruleForm
        ruleForm.value.organId = selectedItem.erpSupplier?.supId || ''; // 供应商ID
        ruleForm.value.linkNumber = selectedItem.number || ''; // 关联单据
        ruleForm.value.accountId = selectedItem.accountId || ''; // 账户ID
        ruleForm.value.billDate = selectedItem.createTime || ''; // 单据日期
    }
    tableData.value = items.map((item) => ({
        barCode: item.barCode,
        commodityUnit: item.materialUnit,
        materialName: item.name,
        depId: item.depotId,
        sku: item.sku,
        standard: item.standard,
        remark: item.remark,
        totalOperNumber: item.totalOperNumber,
        unitPrice: item.wholesaledecimal,
        basicnumber: item.basicnumber,
        allPrice: item.allPrice,
        operNumber: item.operNumber,
        linkId: item.id,
        mid: item.materialId,
        aid: item.materialExtendId,

    }));
    calculateInvoiceAmount();
};





// 提交表单
const submitForm = (status) => {
    const data = {
        erpDepotHead: {
            type: "入库",
            subType: "零售退货",
            defaultNumber: ruleForm.value.number,
            number: ruleForm.value.number,
            // createTime: ruleForm.value.billDate,
            operTime: ruleForm.value.billDate,
            organId: ruleForm.value.supId,
            accountId: ruleForm.value.accountId,
            remark: ruleForm.value.remark,
            backAmount: ruleForm.value.backAmount,
            changeAmount: ruleForm.value.changeAmount,
            linkNumber: ruleForm.value.linkNumber,
            totalPrice: tableData.value.reduce((total, row) => total + parseFloat(row.allPrice || 0), 0),
            status,
        },
        erpDepotItems: tableData.value.map((row) => ({
            id: row.id,
            depotId: row.depotId,
            materialId: row.mid,
            materialExtendId: row.aid,
            materialUnit: row.materialUnit,
            sku: row.sku,
            operNumber: row.operNumber,
            basicNumber: row.basicNumber,
            unitPrice: row.unitPrice,
            allPrice: row.allPrice,
            remark: row.remark,
        })),
    };

    request({
        url: "/sale/updateck",
        method: "put",
        params: { number: ruleForm.value.number },
        data,
        headers: { "Content-Type": "application/json" }
    })
        .then((res) => {
            close();
            ElMessage.success("修改成功");
        })
        .catch((err) => {
            ElMessage.error("修改失败: " + (err.message || "请稍后重试"));
        });
};
// 表格合计
const getSummaries = (param) => {
    const { data } = param;
    const sums = [];
    sums[7] = data.reduce((total, item) => total + Number(item['operNumber']), 0);
    sums[9] = data.reduce((total, item) => total + Number(item['allPrice']), 0);
    return sums;
};



// 弹出商品选择
const Saleinorder = (menu) => {
    title.value = menu.cname;
    visible.value = true;
    router.push(menu.path);
};

// 关闭商品选择页面
const closeAdd = () => {
    visible.value = false;
};

// 关闭添加弹窗
const close = () => {
    emits("close");
};


</script>

<style scoped>
.ant-modal-body {
    padding: 20px;
}

.custom-input {
    width: 100%;
    text-align: center;
    font-size: 20px;
    height: 40px;
    color: brown;
}
</style>